package admin

import (
	"context"
	"strconv"
	"strings"

	"suci-go-zero/common/xerr"
	"suci-go-zero/internal/model"
	"suci-go-zero/internal/svc"
	"suci-go-zero/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserUpdateLogic) UserUpdate(req *types.UpdateUser) error {
	user, err := l.svcCtx.Models.User.FindOne(l.ctx, req.Id)
	if err != nil && err != model.ErrNotFound {
		return errors.Wrap(xerr.NewErrCode(xerr.DB_ERROR), "更新用户数据库出错")
	}
	if user == nil {
		return errors.Wrap(xerr.NewErrCode(xerr.DB_NOT_FOUND_ERR), "更新用户用户不存在")
	}
	user.Avatar = req.Avatar
	user.RealName = req.RealName
	user.Name = req.Name

	roleArry := make([]string, 0)

	for _, roleId := range req.Role {
		roleArry = append(roleArry, strconv.Itoa(roleId))
	}

	user.Roles = strings.Join(roleArry, ",")

	err = l.svcCtx.Models.User.UpdateWithVersion(l.ctx, nil, user)
	if err != nil {
		return errors.Wrap(xerr.NewErrCode(xerr.DB_ERROR), "更新用户数据库出错-1")
	}

	return nil

}
